package com.zhongshengnetwork.rightbe.common.ImageBanner;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GlideRoundTransform;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.lang.activity.SelfImagePreviewActivity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


public class BannerView extends FrameLayout {

    private static final int MSG_LOOP = 1000;
    private static long LOOP_INTERVAL = 2000;
    public ViewPager mViewPager = null;
    private BannerHandler mBannerHandler = null;

    private Activity mActivity;

    private List<View> viewList;
    private List<String> imgList;
    private int viewSize;
    private TextView textView;
    private ListView listview;

    private int currentPosition;

    private int imgH = 0;

    private int imgW = 0;

    private String smallImg; //缩略图

    //标志是否是手势操作造成的滑动
    private boolean mGestureScroll = false;

    private static class BannerHandler extends Handler {
        private WeakReference<BannerView> weakReference = null;

        public BannerHandler(BannerView bannerView) {
            super(Looper.getMainLooper());
            this.weakReference = new WeakReference<BannerView>(bannerView);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (this.weakReference == null) {
                return;
            }
            BannerView bannerView = this.weakReference.get();
            if (bannerView == null || bannerView.mViewPager == null || bannerView.mViewPager.getAdapter() == null || bannerView.mViewPager.getAdapter().getCount() <= 0) {
                return;
            }

            if (bannerView.viewList == null || bannerView.viewList.size() <= 0){
                return;
            }

            if (bannerView.currentPosition >= bannerView.listview.getFirstVisiblePosition() && bannerView.currentPosition <= bannerView.listview.getLastVisiblePosition()){
                if (CustomApplication.customApplication.isGettingData == true){
                    if (hasMessages(MSG_LOOP)){
                        removeMessages(MSG_LOOP);
                    }
                    Log.e("TAG","正在加载轮播不可执行="+bannerView.currentPosition);
                    return;
                }
            }else {
                if (hasMessages(MSG_LOOP)){
                    removeMessages(MSG_LOOP);
                }
                //Log.e("TAG","正在执行轮播不可视的="+bannerView.currentPosition);
                return;
            }

            int curPos = bannerView.mViewPager.getCurrentItem();
            curPos = (curPos + 1) % bannerView.mViewPager.getAdapter().getCount();
            bannerView.mViewPager.setCurrentItem(curPos);
            curPos = curPos % bannerView.viewList.size();
            bannerView.textView.setText((curPos + 1) +" / "+bannerView.viewList.size());
            if (hasMessages(MSG_LOOP)){
                removeMessages(MSG_LOOP);
            }
            //Log.e("TAG","正在执行轮播="+bannerView.currentPosition);
            sendEmptyMessageDelayed(MSG_LOOP, LOOP_INTERVAL);
        }
    }

    public BannerView(Context context) {
        super(context);
        init();
    }

    public BannerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public void startLoop(boolean flag) {
        if (flag) {
            if (mBannerHandler == null) {
                mBannerHandler = new BannerHandler(this);
            }
            mBannerHandler.sendEmptyMessageDelayed(MSG_LOOP, LOOP_INTERVAL);
        } else {
            if (mBannerHandler != null) {
                if (mBannerHandler.hasMessages(MSG_LOOP)) {
                    mBannerHandler.removeMessages(MSG_LOOP);
                    mBannerHandler = null;
                }
            }
        }
    }

    private void init() {
        initViewPager();
        this.addView(mViewPager);
    }

    private void initViewPager() {
        mViewPager = new ViewPager(getContext());
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT
                , ViewGroup.LayoutParams.WRAP_CONTENT);
        mViewPager.setLayoutParams(layoutParams);
        /*
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                //此处返回的position是大数
                if (position == 0 || imgList.isEmpty()) {
                    return;
                }
                int curPos = position;
                curPos = curPos % viewList.size();
                textView.setText((curPos + 1) +" / "+viewList.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        */
        mViewPager.addOnPageChangeListener(mPageListener);

        mViewPager.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        if (mBannerHandler != null) {
                            if (mBannerHandler.hasMessages(MSG_LOOP)) {
                                mBannerHandler.removeMessages(MSG_LOOP);
                            }
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (mBannerHandler != null) {
                            mBannerHandler.sendEmptyMessageDelayed(MSG_LOOP, LOOP_INTERVAL);
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
        });
    }

    public void setAdapter(PagerAdapter adapter) {
        mViewPager.setAdapter(adapter);
        adapter.registerDataSetObserver(mDataObserver);
    }

    private DataSetObserver mDataObserver = new DataSetObserver() {
        @Override
        public void onChanged() {
            super.onChanged();
        }

        @Override
        public void onInvalidated() {
            super.onInvalidated();
        }
    };


    //点击图片处理
    private void onClickImageView(final View view){

        if (CustomApplication.isWatchingImg == true){
            return;
        }
        CustomApplication.isWatchingImg = true;


        Intent intent = new Intent(getContext(), SelfImagePreviewActivity.class);
        intent.putExtra("position",mViewPager.getCurrentItem()%viewSize);
        intent.putExtra("isListImg",true);
        intent.putExtra("imgs",CommonUtils.listToString(imgList));
        //View代表方法传入的控件
        int[] viewLocation = new int[2];
        view.getLocationInWindow(viewLocation);
        int viewX = viewLocation[0]; // x 坐标
        int viewY = viewLocation[1]-(int) (20* ScreenUtils.getScreenDensity(CustomApplication.mContext)); // y 坐标，这里当顶部有状态栏时，要减去状态栏的高度
        intent.putExtra("viewX",viewX);
        intent.putExtra("viewY",viewY);
        intent.putExtra("imgW",imgW);
        intent.putExtra("imgH",imgH);
        getContext().startActivity(intent);
        mActivity.overridePendingTransition(0,0);//可以通过参数设置关闭与要显示的动画效果,0表示无效果.
    }

    public void setDataList(List<String>dataList, ListView l, int position, TextView t, Activity activity, int W, int H, String smallImg){
        this.smallImg = smallImg;
        this.mActivity = activity;
        this.currentPosition = position;
        this.textView = t;
        this.imgH = H;
        this.imgW = W;
        this.listview = l;
        this.imgList = dataList;
        if (this.viewList != null && this.viewList.size() > 0){
            this.viewList.clear();
        }else {
            if (this.viewList == null){
                this.viewList = new ArrayList<View>();
            }
        }
        for(int i = 0; i < dataList.size(); i++){
            RelativeLayout layout = new RelativeLayout(activity);
            layout.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

            ImageView image = new ImageView(activity);
            image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            //设置显示格式
            image.setScaleType(ImageView.ScaleType.CENTER_CROP);
            image.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            Log.e("TAG", "图片是："+dataList.get(i)+CommonUtils.formatString(this.smallImg));
            Glide.with(activity).load(dataList.get(i)+CommonUtils.formatString(this.smallImg)).placeholder(AppThemeUtils.getInstance().getDefaultBitmap()).dontAnimate().transform(new CenterCrop(),new GlideRoundTransform(getContext(), Constant.LangCornerRadius)).into(image);
            layout.addView(image);
            layout.setClickable(true);
            layout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    onClickImageView(view);
                }
            });
            this.viewList.add(layout);
        }
        viewSize = viewList.size();
        textView.setText("1 / "+viewList.size());
        BannerAdapter bannerAdapter = new BannerAdapter(viewList);
        setAdapter(bannerAdapter);
        startLoop(true);
    }

    public void setViewList(List<View> viewList) {
        this.viewList = viewList;
        if (viewList != null && viewList.size() != 0) {
            viewSize = viewList.size();
            BannerAdapter bannerAdapter = new BannerAdapter(viewList);
            setAdapter(bannerAdapter);
        }
    }

    public void setTransformAnim (boolean flag){
        if (flag){
            mViewPager.setPageTransformer(true, new ViewPager.PageTransformer() {
                private static final float MIN_SCALE = 0.75f;
                @Override
                public void transformPage(View view, float position) {
                    int pageWidth = view.getWidth();
                    if (position < -1)
                    { // [-Infinity,-1)
                        // This page is way off-screen to the left.
                        view.setRotation(0);

                    } else if (position <= 1)
                    { // [-1,1]
                        // Modify the default slide transition to shrink the page as well
                        if (position < 0)
                        {

                            float mRot = (20f * position);
                            view.setPivotX(view.getMeasuredWidth() * 0.5f);
                            view.setPivotY(view.getMeasuredHeight());
                            view.setRotation(mRot);
                        } else
                        {

                            float mRot = (20f * position);
                            view.setPivotX(view.getMeasuredWidth() * 0.5f);
                            view.setPivotY(view.getMeasuredHeight());
                            view.setRotation(mRot);
                        }

                        // Scale the page down (between MIN_SCALE and 1)

                        // Fade the page relative to its size.

                    } else
                    { // (1,+Infinity]
                        // This page is way off-screen to the right.
                        view.setRotation(0);
                    }
                }
            });
        }
    }

    public void setLoopInterval(long loopInterval) {
        LOOP_INTERVAL = loopInterval;
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mBannerHandler != null){
            mBannerHandler.removeMessages(MSG_LOOP);
            mBannerHandler = null;
        }
    }

    /**
     * ViewPager滑动监听
     */
    ViewPager.OnPageChangeListener mPageListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            //此处返回的position是大数
            if (position == 0) {
                return;
            }
            Log.e("TAG", "postion是="+position);
            int smallPos = position % viewList.size();
            if (mScrollPageListener != null) {
                mScrollPageListener.onPageSelected(smallPos);
            }
            textView.setText((smallPos + 1) +" / "+viewList.size());
        }

        @Override
        public void onPageScrollStateChanged(int state) {
            onPageScrollStateChange(state);
        }
    };

    /**
     * 手指滑动时暂停自动轮播，手指松开时重新启动自动轮播
     *
     * @param state
     */
    private void onPageScrollStateChange(int state) {

        switch (state) {
            case ViewPager.SCROLL_STATE_IDLE:
                if (!mGestureScroll) {
                    return;
                }
                mGestureScroll = false;
                if (mBannerHandler != null){
                    if (mBannerHandler.hasMessages(MSG_LOOP)) {
                        mBannerHandler.removeMessages(MSG_LOOP);
                    }
                    mBannerHandler.sendEmptyMessageDelayed(MSG_LOOP, 100);
                }
                break;
            case ViewPager.SCROLL_STATE_DRAGGING:
                // 手指滑动时，清除播放下一张，防止滑动过程中自动播放下一张
                mGestureScroll = true;
                if (mBannerHandler != null) {
                    if (mBannerHandler.hasMessages(MSG_LOOP)) {
                        mBannerHandler.removeMessages(MSG_LOOP);
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 滚动监听回调接口
     */

    ScrollPageListener mScrollPageListener;

    public void setScrollPageListener(ScrollPageListener mScrollPageListener) {
        this.mScrollPageListener = mScrollPageListener;
    }

    public interface ScrollPageListener {
        void onPageSelected(int position);
    }

}

